package com.gitee.andy.zpush.node;

import java.util.concurrent.ConcurrentLinkedQueue;

import com.gitee.andy.zpush.kernel.Session;
import com.gitee.andy.zpush.kernel.Session4Server;
import com.gitee.andy.zpush.kernel.SessionContext;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

//@Sharable
public class EchoServerHandler extends ChannelInboundHandlerAdapter {

    //private static final Logger log = LoggerFactory.getLogger(EchoServerHandler.class);

	private SessionContext sessionContext;
	
	private ConcurrentLinkedQueue<Object> msgQueue;

	public EchoServerHandler(SessionContext sessionContext, ConcurrentLinkedQueue<Object> msgQueue)  {
		super();
		this.sessionContext = sessionContext;
		this.msgQueue = msgQueue;
	}

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		sessionContext.add(new Session4Server().bind(ctx));
	}

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) {
		//log.info("receive msg:{}", msg);
		msgQueue.offer(msg);
	}

	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		sessionContext.remove(Session.unbind(ctx));
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
		cause.printStackTrace();
		ctx.close();
	}
}